// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/testing/gtest_utils.h>
#include <pollux/testing/functions/prestosql/function_base_test.h>

using namespace kumo::pollux;
using namespace kumo::pollux::test;
using namespace kumo::pollux::exec;
using namespace kumo::pollux::functions::test;

namespace {

class ArrayFlattenTest : public FunctionBaseTest {
 protected:
  void testExpression(
      const std::string& expression,
      const std::vector<VectorPtr>& input,
      const VectorPtr& expected) {
    auto result = evaluate(expression, make_row_vector(input));
    assertEqualVectors(expected, result);
  }
};

/// Flatten integer arrays.
TEST_F(ArrayFlattenTest, intArrays) {
  const auto baseVector = make_array_vector<int64_t>(
      {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}});

  // Create arrays of array vector using above base vector.
  // [[1, 1], [2, 2], [3, 3]]
  // [[4, 4]]
  // [[5, 5], [6, 6]]
  const auto arrayOfArrays = make_array_vector({0, 3, 4}, baseVector);

  // [1, 1, 2, 2, 3, 3]
  // [4, 4]
  // [5, 5, 6, 6]
  const auto expected =
      make_array_vector<int64_t>({{1, 1, 2, 2, 3, 3}, {4, 4}, {5, 5, 6, 6}});

  testExpression("flatten(c0)", {arrayOfArrays}, expected);
}

/// Flatten arrays with null.
TEST_F(ArrayFlattenTest, nullArray) {
  const auto baseVector = make_nullable_array_vector<int64_t>(
      {{{1, 1}},
       std::nullopt,
       {{3, 3}},
       {{5, std::nullopt}},
       {{std::nullopt, 6}}});

  // Create arrays of array vector using above base vector.
  // [[1, 1], null, [3, 3]]
  // null
  // [[5, null], [null, 6]]
  const auto arrayOfArrays = make_array_vector({0, 3, 3}, baseVector, {1});

  // [[1, 1, 3, 3]]
  // null
  // [[5, null, null, 6]]
  const auto expected = make_nullable_array_vector<int64_t>(
      {{{1, 1, 3, 3}}, std::nullopt, {{5, std::nullopt, std::nullopt, 6}}});

  testExpression("flatten(c0)", {arrayOfArrays}, expected);
}
} // namespace
